//
//  HWRankListViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/10.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView

class HWRankListViewController: HWBaseViewController {

    private var topView = HWRankListTopView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(HWRankCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.rowHeight = 90*widthScale
        return tableView
    }()

    var httpManager = HWHomeNormalHttpManager()
    var gameHttpManager = HWGameCenterHttpManager()
    var tempModel:[HWHomeGameModel]?{
        didSet{
            guard let allGames = tempModel, allGames.count > 0 else { return }
            var models = [HWHomeGameModel]()
            for (index, md) in allGames.enumerated() {
                let model = md
                model.sort = index
                models.append(model)
            }
            self.dataModel = models
            tableView.reloadData()
        }
    }
    var dataModel:[HWHomeGameModel]?
    
    
    private var pageIndex = 1
    private var gameType:String = "0"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = "#F7F8FA".toColor
        view.subviews{
            topView
            tableView
        }
        
        loadData()
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        topView.leading(0).trailing(0).top(0).height(38*widthScale)
        tableView.leading(0).trailing(0).bottom(0).top(38*widthScale)
        topView.updateCateData = { type in
            self.gameType = type
            self.loadNewData()
        }
    }
    
}

//MARK: - loadData
extension HWRankListViewController {

    private func loadData(){
        
        tableView.mj_footer?.endRefreshing()
        httpManager.getHomeNormalInfo(type: "5", gameType:self.gameType, pageIndex) { model in
            self.tableView.mj_header?.endRefreshing()
            self.tempModel = model.allGames?.games
            let tempArray = model.game_types
            tempArray[0].isSel = true
            self.topView.sourceData = tempArray
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
    
    private func addRefresh() {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    @objc private func loadNewData(){
        pageIndex = 1
        self.tempModel?.removeAll()
        self.dataModel?.removeAll()
        tableView.mj_footer?.endRefreshing()
        httpManager.getHomeNormalInfo(type: "5", gameType:self.gameType, pageIndex) { model in
            self.tableView.mj_header?.endRefreshing()
            self.tempModel = model.allGames?.games
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
    }
    
    @objc private func loadMoreData(){
        pageIndex += 1
        
        httpManager.getHomeNormalInfo(type: "5", gameType:self.gameType, pageIndex) { model in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            if (model.allGames?.games?.count ?? 0) > 0 {
                for mod in (model.allGames?.games)! {
                    self.tempModel?.append(mod)
                }
            } else {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            self.tableView.reloadData()
        } failure: { error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
        }
        
    }
}


//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWRankListViewController: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return dataModel?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HWRankCell", for: indexPath) as! HWRankCell
        cell.model = dataModel?[indexPath.row]
        cell.gameType = self.gameType
        cell.yuyueGameBlock = { id in
            self.gameHttpManager.getAddAppointment(gameId: id) { success in
                self.loadNewData()
            } failure: { errorString in
                self.view.showHUD(title: errorString)
            }
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailVC = HWGameDetailController()
        detailVC.gameId = dataModel?[indexPath.row].id ?? ""
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

}

extension HWRankListViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
